package br.unesp.rc.rafaelt.server.businnes.services;

import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicLong;

import org.apache.commons.lang3.Validate;
import org.springframework.stereotype.Service;

import br.unesp.rc.rafaelt.server.model.bean.Author;

@Service
public class AuthorServiceImpl implements AuthorService {
	private final AtomicLong USER_ID_SEQ = new AtomicLong();
	private final ConcurrentMap<Long, Author> authorsMap = new ConcurrentHashMap<Long, Author>();
	
	@Override
	public Author create(Author author) {
		author.setId(USER_ID_SEQ.incrementAndGet());
		authorsMap.put(author.getId(), author);
		return author;
	}

	@Override
	public Author read(long authorId) {
		return authorsMap.get(authorId);
	}

	@Override
	public Author update(Author author) {
		Author updatedAuthor = authorsMap.replace(author.getId(), author);
		Validate.isTrue(updatedAuthor != null, "Unable to find author with id: " + author.getId());
		return updatedAuthor;
	}

	@Override
	public Author delete(long authorId) {
		Author removedAuthor = authorsMap.remove(authorId);
		Validate.isTrue(removedAuthor != null, "Unable to find author with id: " + authorId);
		return removedAuthor;
	}

	@Override
	public Collection<Author> list() {
		return authorsMap.values();
	}
}
